﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace NFinal.Common.Plugin
{
    /// <summary>
    /// 宿主项目程序集信息
    /// </summary>
    public class HostContext
    {
        private static SortedList<string, AssemblyName> hostRefAssemblyNames = null;
        private static Assembly hostAssembly = null;
        private static object _lock = new object();
        public static SortedList<string, AssemblyName> GetHostRefAssemblyNames(Assembly hostAssembly)
        {
            if (hostRefAssemblyNames == null)
            {
                lock (_lock)
                {
                    if (hostRefAssemblyNames == null)
                    {
                        HostContext.hostAssembly = hostAssembly;
                        AssemblyName hostAssemblyName = hostAssembly.GetName();
                        SortedList<string, AssemblyName> hostRefAssemblyNamesTmp = new SortedList<string, AssemblyName>();
                        hostRefAssemblyNamesTmp.Add(hostAssemblyName.Name, hostAssemblyName);
                        AssemblyName[] referencedAssemblies = hostAssembly.GetReferencedAssemblies();
                        foreach (var referenceAssembly in referencedAssemblies)
                        {
                            hostRefAssemblyNamesTmp.Add(referenceAssembly.Name, referenceAssembly);
                        }
                        hostRefAssemblyNames = hostRefAssemblyNamesTmp;
                    }
                }
            }
            return hostRefAssemblyNames;
        }
        public static bool HasAssembly(AssemblyName assemblyName)
        {
            if (hostRefAssemblyNames.TryGetValue(assemblyName.Name, out AssemblyName hostAssemblyName))
            {
                if (hostAssemblyName.FullName == assemblyName.FullName)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
